<template>
    <el-tree-select ref="treeRef" v-model="value" :data="treeData" check-strictly :render-after-expand="false"
        default-expand-all node-key="id" @node-click="handleNodeClick" :default-checked-keys="treeDefaultChecked"
        :disabled="disabled" clearable/>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs, watch } from 'vue'
import request from '/@/utils/request'

export default defineComponent({
    name: 'VpBaseSelectTree',
    emits: ['treeSelected'],
    props: {
        parentId: String,
        selectedId: String,
        disabled: {
            type: Boolean,
            default: false,
        },
    },
    setup(props, context) {
        const state = reactive({
            loading: false,
            treeData: [],
            treeDefaultChecked: [],
            value: { id: '', label: '' },
        })
        const loadData = async () => {
            state.loading = true
            const res = await request.get('/system/base/treeList', {
                params: {
                    parentId: (props.parentId || '')
                }
            })
            state.treeData = res?.data || []
            state.loading = false
            // .then(res => {

            // }).finally(() => {
            //     state.loading = false
            // })
        }
        const init = () => {
            state.treeData = [];
            state.treeDefaultChecked = [];
        }
        watch(() => props.parentId, () => {
            init();
            loadData();
        })
        watch(() => props.selectedId, () => {
            state.value = {
                id: props.selectedId || '',
                label: findNameById(props.selectedId) || '',
            }
        })
        onMounted(async() => {
            await loadData();
            state.value = {
                id: props.selectedId || '',
                label: findNameById(props.selectedId) || '',
            }
        })
        const treeRef = ref();
        const handleNodeClick = (data: any) => {
            context.emit("treeSelected", {
                id: data.id,
                label: data.label,
            });
        }
        const findNameById = (targetId: string | undefined) => {
            const traverse = (node) => {
                if (node.id === targetId) {
                    return node.label;
                }
                if (node.children && Array.isArray(node.children) && node.children.length > 0) {
                    for (const child of node.children) {
                        const result = traverse(child) as string;
                        if (result !== null) {
                            return result;
                        }
                    }
                }
                return null;
            };
            if (Array.isArray(state.treeData)) {
                for (const node of state.treeData) {
                    const result = traverse(node);
                    if (result !== null) {
                        return result;
                    }
                }
            }
            
            return '';
        }

        return {
            ...toRefs(state),
            ...toRefs(props),
            handleNodeClick,
            treeRef,
        }
    }
})
</script>
